<template>
  <div class="container">
    <el-card class="personal-info">
      <template #header>
        <div class="info-heading">
          <h2>个人信息</h2>
        </div>
      </template>
      <el-avatar :src="'http://192.168.61.163:9090'+avatarUrl" class="user-avatar" />
      <el-upload
        class="avatar-uploader"
        action="http://192.168.61.163:9090/api/user/uploadAvatar"
        :headers="uploadHeaders"
        :method="'post'"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        <el-button type="primary">上传头像</el-button>
      </el-upload>
      <el-table :data="[userData]" border>
        <el-table-column prop="id" label="用户ID"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column label="这里没有密码😀">
          <template #default="scope">
            <span v-if="showPassword">{{ userData.password }}</span>
            <span v-else>******</span>
            <el-button @click="toggleShowPassword" type="text">{{ showPassword ? '说了不会给你看的啦😂' : '想看密码？🤔' }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column prop="role" label="身份"></el-table-column>
      </el-table>
    </el-card>

    <el-card class="edit-info">
      <template #header>
        <div class="info-heading2">
          <h3>个人信息修改</h3>
        </div>
      </template>
      <div class="input-field">
        <el-select v-model="selectedField" placeholder="选择要修改的内容" @change="showInputField">
          <el-option label="用户名" value="username"></el-option>
          <el-option label="密码" value="password"></el-option>
          <el-option label="电话" value="phone"></el-option>
        </el-select>
        <div v-if="showInput" class="input-info">
          <span v-if="selectedField !== 'password'">请输入您的{{ fieldMap[selectedField] }}:</span>
          <span v-else>请输入您的旧密码和新密码:</span>
          <el-input v-if="selectedField !== 'password'" v-model="inputValue" :type="inputType" :placeholder="'请输入您的' + fieldMap[selectedField]"></el-input>
          <div v-else>
            <el-input v-model="oldPassword" type="password" placeholder="请输入您的旧密码"></el-input>
            <el-input v-model="newPassword" type="password" placeholder="请输入您的新密码"></el-input>
          </div>
          <el-button type="primary" @click="editInfo">确认修改</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>



<script lang="ts">
import { ref } from 'vue';
import request from '../utils/request';
import type { UploadProps } from 'element-plus';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';


//const imageUrl = ref('');
export default {
  data() {
    return {
      showPassword: false,
      userData: {},
      avatarUrl: '',
      selectedField: '',
      showInput: false,
      oldPassword: '',
      newPassword: '',
      inputValue: '',
      inputType: 'text',
      fieldMap: {
        username: '用户名',
        password: '密码',
        phone: '电话号码',
      },
    };
  },
  computed: {
    uploadHeaders() {
      return {
        token:localStorage.getItem('token'),
      };
    },
  },
  created() {
    this.loadUserData();
  },
  methods: {
    async loadUserData() {
      try {
        const id=localStorage.getItem('userid');
        const response = await request.get('api/user/select',{params:{
          id:id,
        }});
        this.userData = response.data[0];
        this.avatarUrl = response.data[0].avatar;
      } catch (error) {
        console.error('加载用户信息失败', error);
      }
    },
    showInputField() {
      this.showInput = true;
      this.inputValue = this.userData[this.selectedField];
      this.oldPassword = '';
      this.newPassword = '';
      this.inputType = this.selectedField === 'password' ? 'password' : 'text';
    },
    toggleShowPassword() {
      this.showPassword = !this.showPassword;
    },
    async editInfo() {
      let url;
      let params;
      /*
      if (this.selectedField === 'username') {
        url = 'api/user/updateUsername';
        params = { username: this.inputValue };
      } else if (this.selectedField === 'password') {
        url = 'api/user/updatePassword';
        params = { oldPassword: this.oldPassword, newPassword: this.newPassword };
      } else if (this.selectedField === 'phone') {
        url = 'api/user/updatePhone';
        params = { phone: this.inputValue };
      }
      try {
        const response = await request.put(url,params);
        console(url,"/n",params);
        if (response.data.code === '200') {
          console.log('修改成功', response.data);
          this.loadUserData();
          this.showInput = false;
        } else {
          console.error('修改失败', response.data.msg);
        }
      } catch (error) {
        console.error('修改请求失败', error);
      }*/
      if (this.selectedField === 'username') {
        url = 'api/user/updateUsername';
        params={
          username:this.inputValue,
        };
        try{
          const response = await request.put(url,null,{params:{
            username:this.inputValue,
          }});
          if(response.data==="200"){
            console.log('修改用户名成功', response.data);
            this.loadUserData();
            //location.reload();
          }else{
            console.error('修改用户名失败', error);
          }
        }catch(error){
          console.error('修改用户名失败', error);
        }
      } else if (this.selectedField === 'password') {
        url = 'api/user/updatePassword';
        params={
          oldPassword: this.oldPassword,
          newPassword: this.newPassword,
        };
        try{
          const response = await request.put(url,params);
          if(response.data==="200"){
            console.log('修改成功', response.data);
            this.loadUserData();
            //location.reload();
          }else{
            console.error('修改密码失败，请检查旧密码', error);
          }
        }catch(error){
          console.error('修改密码失败，请检查旧密码', error);
        }
      } else if (this.selectedField === 'phone') {
        url = 'api/user/updatePhone';
        params = {
          phone: this.inputValue,
        };
        try {
        const response = await request.put(url, null,{params:{
          phone:this.inputValue,
        }});
        if(response.data==="200"){
        console.log('修改成功', response.data);
        this.loadUserData();
        //location.reload();
        this.showInput = false;
      }
      } catch (error) {
        console.error('修改失败', error);
      }
      }
      if (this.selectedField === 'password'){
      this.$router.push('/');
      //location.reload();
      localStorage.clear;
      this.$router.push('/');
      }
    },

    handleAvatarSuccess(response, file) {
      if (response.code === '200') {
        this.avatarUrl = response.data.avatar; // 使用后端返回的新头像URL
        this.loadUserData();
        console.log(avatarUrl);
      } else {
        console.error('上传头像失败', response.msg);
      }
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return (isJPG || isPNG) && isLt2M;
    },
  },
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.personal-info, .edit-info {
  width: 100%;
  max-width: 600px;
  margin-bottom: 20px;
}

.input-field {
  margin-top: 20px;
}

.info-heading, .info-heading2 {
  text-align: center;
  margin-bottom: 20px;
}

.el-table {
  height: 100%; /* 使表格占满卡片高度 */
}

.user-avatar {
  display: block;
  margin: 20px auto;
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

.avatar-uploader {
  text-align: center;
  margin-bottom: 20px;
}
</style>